package com.linewell.utils;

import com.linewell.entity.UserInfo;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;

/**
 * @Title: ssm2
 * @description:
 * @author: hyuhuang@linewell.com
 * @since:2018/5/4
 */
public class EmailUtils {

    private static final String FROM = "401963883@163.com";

    /**
     * 发送重设密码链接的邮件
     */
    public static void sendResetPasswordEmail(UserInfo userInfo) {
        Session session = getSession();
        MimeMessage message = new MimeMessage(session);
        try {
            message.setSubject("找回您的帐户与密码");
            message.setSentDate(new Date());
            message.setFrom(new InternetAddress(FROM));
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(userInfo.getEmail()));
            message.setContent("要使用新的密码, 请使用以下链接启用密码:<br/><a href=' http://127.0.0.1:8090/resetPwd?userId="+ userInfo.getUserId()+ "&CHECK_CODE=" + Md5Util.getMD5Code(userInfo.getPwd()) +"'>点击重新设置密码</a>","text/html;charset=utf-8");
            // 发送邮件
            Transport.send(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Session getSession() {
        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.smtp.host", "smtp.163.com");
        props.setProperty("mail.smtp.port", "25");
        props.setProperty("mail.smtp.auth", "true");
        Session session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                String password = "huyuhuang1";
                return new PasswordAuthentication(FROM, password);
            }

        });
        return session;
    }
}